package com.medvalley.tcm.service.impl;

import com.google.common.collect.Lists;
import com.medvalley.tcm.dao.DepartmentDao;
import com.medvalley.tcm.domain.Department;
import com.medvalley.tcm.service.DepartmentService;
import com.medvalley.tcm.vo.outputvo.DepartmentOutputVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author linsong
 * @date 2019/4/28 17:54
 **/
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentDao departmentDao;

    @Override
    public List<DepartmentOutputVo> findAllDepartments() {
        List<Department> departments = departmentDao.findAll();
        List<Department> level1Department = departments.stream().filter(e -> e.getParentNo().equals("0")).collect(Collectors.toList());
        List<Department> level2Department = departments.stream().filter(e -> !e.getParentNo().equals("0")).collect(Collectors.toList());

        Map<String, List<Department>> level1Map = level2Department.stream().collect(Collectors.groupingBy(Department::getParentNo));

        List<DepartmentOutputVo> outputVos = Lists.newArrayList();
        for (Department d : level1Department) {
            DepartmentOutputVo l1outputVo = new DepartmentOutputVo();
            l1outputVo.setId(d.getDNo());
            l1outputVo.setDepartment(d.getDName());
            List<DepartmentOutputVo> sublist = Lists.newArrayList();
            if (level1Map.get(d.getDNo()) != null) {
                for (Department d2 : level1Map.get(d.getDNo())) {
                    DepartmentOutputVo l2outputVo = new DepartmentOutputVo();
                    l2outputVo.setId(d2.getDNo());
                    l2outputVo.setDepartment(d2.getDName());
                    sublist.add(l2outputVo);
                }
            }
            l1outputVo.setDepartmentDataList(sublist);
            outputVos.add(l1outputVo);
        }
        return outputVos;
    }
}
